from typing import Optional

from fastapi import Cookie, Depends, FastAPI

app = FastAPI()


# 依赖1
def query_extractor(q: Optional[str] = None):
    return q


# 如果依赖1不存在，则使用新的依赖
def query_or_cookie_extractor(
        q: str = Depends(query_extractor), last_query: Optional[str] = Cookie(None)
):
    if not q:
        return last_query
    return q


# 依赖注入
@app.get("/items/")
async def read_query(query_or_default: str = Depends(query_or_cookie_extractor)):
    return {"q_or_cookie": query_or_default}
